// src.module.mobileh5.module.js

var MongoDB = require('./DB/mongodb');
var mongoUtil = require('../helper/MongoUtil');
var dateUtil = require('../helper/DateformatHelper.js');
var log = require('log4js').getLogger("index");

exports.save = function (req, res, callback) {
    var fields = {};
    if(req.body.name){
        fields.name = req.body.name;
    }
    if(req.body.state){
        fields.state = req.body.state;
    }
    if(req.body.description){
        fields.description = req.body.description;
    }
    if(req.body.content || req.body.setting){
        fields.content = JSON.stringify(req.body);
    }
    if(req.body.is_del){
        fields.is_del = req.body.is_del;
    }

    if(req.query._id){
        // id,name,create_time,create_by,state,description,content,is_del,modify_by,modify_time  content:JSON.stringify(req.body)
        fields.modify_by = req.session.user.username;
        fields.modify_time = dateUtil.getCurrentTime();
        MongoDB.update('mobileh5', {_id:req.query._id}, fields,function(err, result){
            if(err) log.error(err);
            callback(err, result);
        })
    }else{
        fields.state = 0;
        fields.is_del = 0;
        fields.create_by = req.session.user.username;
        fields.create_time = dateUtil.getCurrentTime();
        MongoDB.save('mobileh5', fields,function(err, result){
            if(err) log.error(err);
            callback(err, result);
        })
    }
};

exports.delete = function (req, res, callback) {
    MongoDB.remove('mobileh5', {_id:req.query._id},function(err, result){
        if(err) log.error(err);
        callback(err, result);
    });
};

exports.queryById = function (req, res, callback) {
    // var conditions = {};
    // conditions._id = req.query._id;
    MongoDB.findById('mobileh5', req.query._id, function (err, result) {
        if(err) log.error(err);
        callback(err, result);
    });
};

exports.queryByPage = function (req, res, callback) {
    req.page = {'currentPage':req.query.currentPage||1,'pageSize':req.query.pageSize||10};
    req.page.pageSize = parseInt(req.page.pageSize);
    var conditions = {}, options ={}, p = req.query;
    options.limit = req.page.pageSize;

    if(p.state) {
        conditions.state = p.state;
    }
    if(p._id){
        conditions._id = p._id;
    }
    if (p.name){
        conditions.name = mongoUtil.like(p.name);
    }
    if (p.is_del){
        conditions.is_del = p.is_del;
    }else{
        conditions.is_del = 0;
    }
    MongoDB.where('mobileh5',conditions,options,function(err, result){
        if(err) log.error(err);
        callback(err, result);
    });
};